package _13_哈希表;

import java.util.HashMap;
import java.util.Map;

public class _166_分数到小数 {

    public static void main(String[] args) {
        _166_分数到小数 v = new _166_分数到小数();
        System.out.println(v.fractionToDecimal(4, 333));

    }

    // 对于遇到相同的除数，保存到hash表中
    public String fractionToDecimal(int numerator, int denominator) {
        long a = numerator, b = denominator;
        Map<Long, Integer> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        if (a < 0 && b >= 0 || a > 0 && b < 0) {
            sb.append("-");
        }
        a = Math.abs(a);
        b = Math.abs(b);
        while (true) {
            long mul = a / b;
            long remain = a % b;
            sb.append(mul);
            if (remain == 0) break;
            if (first) {
                sb.append(".");
                first = false;
            }
            a = remain * 10;
            Integer index = map.get(a);
            if (index != null) {
                sb.insert(index, "(");
                sb.append(")");
                break;
            }
            map.put(a, sb.length());
        }
        return sb.toString();
    }

}
